<?php

namespace app\index\controller;

use app\common\controller\Log;
use app\common\model\Levels;
use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\Recharge;
use app\common\model\Withdrawal;
use think\Db;
use think\Validate;
use app\common\api\controller\Bonus;

class TradingHall extends Home
{
    protected $beforeActionList = [
        'check_load'
    ];

    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 提现申请
     */
    public function wdReply()
    {
        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }
        $uid = $this->uid;
        $userinfo = Member::get($uid);

        $rule = get_bonus_rule();//交易规则

        $nowday = date('w');
        $allowday = explode(',', get_bonus_rule('wd_time'));
        if (!in_array($nowday, $allowday)) {
            $this->apiError('今日不可提现！');
        }
        $wdinfo = Db::name('withdrawal')->where(['userid' => $uid, 'status' => 0])->find();
        if (!empty($wdinfo)) {
            $this->apiError('已申请过提现，等申请批准后方可再次申请!');
        }
        $today = strtotime('today');
        $map['userid'] = $uid;
        $moneytype = input('moneytype', 2);
        $map['handtime'] = ['egt', $today];
        $count = Db('withdrawal')->where($map)->count();
        if ($count >= 5) {
            $this->apiError('一天最多只能提现五次！');
        }
        $data = input('post.');
        $validate = Validate('withdrawal');
        if (!$validate->check($data)) {
            $this->apiError($validate->getError());
        }
        if (!$data['password']) {
            $this->apiError('请输入提现密码');
        }
        if ($data['password'] != $userinfo['psd2']) {
            $this->apiError('提现密码输入错误');
        }
        unset($data['password']);

//            if ($data['phone'] != session('phone_verify_code')) {
//                $this->error('手机验证码错误');
//            }
//            unset($data['phone']);
//            session('phone_verify_code', null);

        $money = $data['money'];
        $data['userid'] = $uid;
        $data['usernumber'] = $userinfo['usernumber'];

        if ($userinfo['hasmoney'] < $money) {
            $this->apiError('提现金额大于账户余额');
        }

        if ($rule['min_wd'] > $money) {
            $this->apiError('提现金额小于起提额度');
        }

        if ($money % $rule['multiple_wd']) {
            $this->apiError("提现金额必须是{$rule['multiple_wd']}的整数倍");
        }

        $fee = $money * $rule['fee_wd'] * 0.01;
        $data['fee'] = $fee;
        $data['createtime'] = time();
        $data['status'] = 0;
        $data['money'] = $money - $fee;

        unset($data['token']);
        Db::startTrans();
        try {
            Db('withdrawal')->insert($data);
            Db('member')->where(array('uid' => $uid))->setDec('hasmoney', $money);
            $hasmoney = Db('member')->where(array('uid' => $uid))->value('hasmoney');
            $type_arr = array('recordtype' => 0, 'moneytype' => $moneytype, 'changetype' => 22);
            $money_arr = array('money' => $money, 'hasmoney' => $hasmoney);
            money_change($type_arr, $userinfo, get_com(), $money_arr);

            // 提交事务
            Db::commit();
            $this->apiSuccess('提现申请成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->apiError('申请失败');
        }
    }

    /**
     * 根据银行卡得到银行名称
     */
    public
    function getBankName()
    {
        if (request()->isPost()) {
            $banknumber = input('banknumbe');
            $str = substr($banknumber, 0, 6);
            $lists = config('BANKLIST');
            $bankname = $lists[$str];
            if ($bankname) {
                $this->success($bankname);
            } else {
                $this->error('该卡号错误！');
            }

        } else {
            $this->error('非法操作！');
        }
    }

    /**
     * 提现记录
     */
    public
    function wdRecord()
    {
        $uid = is_login();
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $maps['userid'] = $map['userid'] = $uid;

        $list = Db('withdrawal')->where($map)->order('createtime desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        if (request()->isMobile()) {
            $list = Db('withdrawal')->where($map)->order('createtime desc')->select();
        }
        $this->assign('_list', $list);
        $this->assign('page', $page);

        $this->searchCondition($maps);

        $this->assign('title', '提现');
        return $this->fetch('wdrecord');
    }

    /**
     * 闪兑
     */
    public function tf()
    {
        $password = input('password');
        $uid = $this->uid;
        $memberModel = Member::find($uid);
        if ($memberModel->psd2 != $password) {
            $this->apiError('支付密码错误！');
        }
        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();

        $money1 = input('money1');
        $money2 = input('money2');
        if ($money1 <= 0 && $money2 <= 0) {
            $this->apiError('参数错误！');
        }

        $total_tdb = get_bonus_rule('total_tdb');
        $total_wealth = get_bonus_rule('total_wealth');
        if ($total_tdb == 0) {
            $rate = 1;
        } else {
            $rate = round($total_wealth / $total_tdb, 2);
        }
        if ($money1 > 0) {
            if ($memberFinanceModel->hastdb < $money1) {
                $this->apiError('通兑宝余额不足！');
            }
            $tf_fee = get_bonus_rule('tf_fee');
            $tf_rate1 = get_bonus_rule('tf_rate1');
            $tf_rate2 = get_bonus_rule('tf_rate2');

            $wealth = $money1 * (1 - $tf_fee) * $rate * $tf_rate1;
            $green = $money1 * (1 - $tf_fee) * $rate * $tf_rate2;

            Db::startTrans();
            try {
                $memberFinanceModel->hastdb -= $money1;
                $memberFinanceModel->haswealth += $wealth;
                $memberFinanceModel->allwealth += $wealth;
                $memberFinanceModel->hasgreen += $green;
                $memberFinanceModel->allgreen += $green;

                $memberFinanceModel->save();

                $this->bonusRuleModel->total_tdb += $money1 * (1 - $tf_fee);
                $this->bonusRuleModel->save();

                Db::commit();

            } catch (\Exception $e) {
                Db::rollback();
                $this->apiError('兑换失败！');
            }

            $type_arr = array('recordtype' => 0, 'moneytype' => 2, 'changetype' => 23);
            $money_arr = array('money' => $money1, 'hasmoney' => $memberFinanceModel->hastdb);
            money_change($type_arr, $memberFinanceModel->uid, $memberFinanceModel->uid, $money_arr);

            $type_arr = array('recordtype' => 1, 'moneytype' => 3, 'changetype' => 23);
            $money_arr = array('money' => $wealth, 'hasmoney' => $memberFinanceModel->haswealth);
            money_change($type_arr, $memberFinanceModel->uid, $memberFinanceModel->uid, $money_arr);

            $type_arr = array('recordtype' => 1, 'moneytype' => 8, 'changetype' => 23);
            $money_arr = array('money' => $green, 'hasmoney' => $memberFinanceModel->hasgreen);
            money_change($type_arr, $memberFinanceModel->uid, $memberFinanceModel->uid, $money_arr);
        }

        if ($money2 > 0) {
            if ($memberFinanceModel->haswealth < $money2) {
                $this->apiError('财富通余额不足！');
            }
            $money = round($money2 / $rate, 4);
            Db::startTrans();
            try {
                $memberFinanceModel->haswealth -= $money2;
                $memberFinanceModel->hastdb += $money;
                $memberFinanceModel->alltdb += $money;

                $memberFinanceModel->save();

                $this->bonusRuleModel->total_wealth += $money2;
                $this->bonusRuleModel->save();

                Db::commit();

            } catch (\Exception $e) {
                Db::rollback();
                $this->apiError('兑换失败！');
            }

            $type_arr = array('recordtype' => 0, 'moneytype' => 3, 'changetype' => 24);
            $money_arr = array('money' => $money2, 'hasmoney' => $memberFinanceModel->haswealth);
            money_change($type_arr, $memberFinanceModel->uid, $memberFinanceModel->uid, $money_arr);

            $type_arr = array('recordtype' => 1, 'moneytype' => 2, 'changetype' => 24);
            $money_arr = array('money' => $money, 'hasmoney' => $memberFinanceModel->hastdb);
            money_change($type_arr, $memberFinanceModel->uid, $memberFinanceModel->uid, $money_arr);

        }

        $this->apiSuccess('兑换成功！');
    }

    /**
     * 转币（活跃值兑换通兑宝，通兑宝兑换活跃值）
     */
    public function tfReply()
    {
        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }
        $password = input('password');
        $uid = $this->uid;
        $memberModel = Member::find($uid);
        if ($memberModel->psd2 != $password) {
            $this->apiError('支付密码错误！');
        }
        $userrank = Member::where('uid', $uid)->value('userrank');
        $bonusRole = get_bonus_rule();//交易规则
        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
//        Log::insertLog($memberFinanceModel->hasgrowth);
//        Log::insertLog($bonusRole['min_growth']);

        $tftype = input('tftype', 1);
        if ($tftype == 1 && $memberFinanceModel->hasgrowth < $bonusRole['min_growth']) {
            $this->apiError('成长值余额不足！');
        }
        $money = input('money', 0);                                  //转入用户
        if ($money <= 0) {
            $this->apiError('转币额度必须大于零！');
        }

        switch ($tftype) {
            //活跃值兑换通兑宝，扣费
            case 1:
                $outfiled = 'hasactive';
                $infiled = 'hastdb';
                $outmoneytype = 1;
                $inmoneytype = 2;
                $outmoney = $money;
                $rate = Levels::where('id', $userrank)->value('active_tdb_rate');
                $inmoney = $money * (1 - $rate);
                $multipleWd = $bonusRole['multiple_wd'];
                break;
            //通兑宝兑换活跃值
            case 2:
                $outfiled = 'hastdb';
                $infiled = 'hasactive';
                $outmoneytype = 2;
                $inmoneytype = 1;
                $outmoney = $money;
                $inmoney = $money;
                $multipleWd = $bonusRole['multiple_wd'];
                break;
            default:
                $this->apiError('非法操作！');
                break;
        }

        if ($memberFinanceModel->$outfiled < $money) {
            $this->error('转币金额大于账户余额');
        }

        if ($bonusRole['min_tf'] > $money) {
            $this->error('转币金额小于最小转币金额');
        }

//        if ($money % $multipleWd) {
//            $this->error("转币金额必须是{$multipleWd}的整数倍");
//        }

        $sql1 = "update zx_member_finance  set {$outfiled} = {$outfiled}-{$outmoney} where uid={$uid}";
        switch ($inmoneytype) {
            case 1:
                $sql2 = "update zx_member_finance  set {$infiled} = {$infiled}+{$inmoney},allactive = allactive + {$inmoney} where uid={$uid}";
                break;
            case 2:
                $sql2 = "update zx_member_finance  set {$infiled} = {$infiled}+{$inmoney},alltdb = alltdb + {$inmoney} where uid={$uid}";
                break;
        }

        Db::startTrans();
        try {
            Db::execute($sql1);
            Db::execute($sql2);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $this->apiError('转币失败');
        }

        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
        $type_arr = array('recordtype' => 0, 'moneytype' => $outmoneytype, 'changetype' => 33);
        $money_arr = array('money' => $outmoney, 'hasmoney' => $memberFinanceModel->$outfiled);
        money_change($type_arr, $uid, $uid, $money_arr);

        $type_arr = array('recordtype' => 1, 'moneytype' => $inmoneytype, 'changetype' => 33);
        $money_arr = array('money' => $inmoney, 'hasmoney' => $memberFinanceModel->$infiled);
        money_change($type_arr, $uid, $uid, $money_arr);

        $this->apiSuccess('转币成功');

    }

    /**
     * 同币种转币
     */
    public function tfReply1()
    {
        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }
        $data = input('post.');
        $uid = $this->uid;
        $memberModel = Member::get($uid);
        if (!$data['mobile']) {
            $this->apiError('必须输入对方手机号码！');
        }
        if (!$data['code']) {
            $this->apiError('必须输入短信验证码！');
        }
        $res = $this->checkCode($memberModel->mobile, $data['code']);
        if ($res['status'] == 0) {
            $this->apiError($res['msg']);
        }

        $tuid = Member::where('mobile', $data['mobile'])->value('uid');
        if (!$tuid) {
            $this->apiError('对方账户不存在！');
        }


        if ($uid == $tuid) {
            $this->apiError('不能自己转给自己！');
        }

        $money = (float)$data['money'];
        if ($money <= 0) {
            $this->apiError('转币额度必须大于零！');
        }

        $memberFinanceModel = MemberFinance::find($uid);
        $bonusRole = get_bonus_rule();//交易规则

        $tftype = input('tftype', 3);
        $flow_rate = 'flow_rate' . $tftype;
        $min_flow = 'min_flow' . $tftype;
        $max_flow = 'max_flow' . $tftype;

        switch ($tftype) {
            case 3:
                $filed = 'haswealth';
                $inmoney = $money * (1 - $bonusRole[$flow_rate]);
                break;
            case 6:
                $filed = 'haszzt';
                $inmoney = $money;
                $money = $money * (1 + $bonusRole[$flow_rate]);
                break;
            default:
                $this->apiError('非法操作！');
                break;

        }

        if ($memberFinanceModel->$filed < $money) {
            $this->apiError('转币金额大于账户余额');
        }

        if ($bonusRole[$min_flow] > $money) {
            $this->apiError('转币金额小于最小转币金额');
        }
        if ($bonusRole[$max_flow] < $money) {
            $this->apiError('转币金额大于最大转币金额');
        }

//        if ($money % $bonusRole['multiple_tf']) {
//            $this->error("转币金额必须是{$bonusRole['multiple_tf']}的整数倍");
//        }

        $sql1 = "update zx_member_finance  set {$filed} = {$filed}-{$money} where uid={$uid}";
        switch ($tftype) {
            case 3:
                $sql2 = "update zx_member_finance  set {$filed} = {$filed}+{$inmoney},allwealth = allwealth + {$inmoney} where uid={$tuid}";
                break;
            case 6:
                $sql2 = "update zx_member_finance  set {$filed} = {$filed}+{$inmoney},allwealth = allwealth + {$inmoney} where uid={$tuid}";
                break;
            default:
                $this->apiError('非法操作！');
                break;
        }

        Db::startTrans();
        try {
            Db::execute($sql1);
            Db::execute($sql2);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->apiError('扣币失败！');
        }

        $memberFinanceModel = MemberFinance::find($uid);
        $type_arr = array('recordtype' => 0, 'moneytype' => $tftype, 'changetype' => 34);
        $money_arr = array('money' => $money, 'hasmoney' => $memberFinanceModel->$filed);
        money_change($type_arr, $uid, $tuid, $money_arr);

        $tmemberFinanceModel = MemberFinance::find($tuid);
        $type_arr = array('recordtype' => 1, 'moneytype' => $tftype, 'changetype' => 34);
        $money_arr = array('money' => $inmoney, 'hasmoney' => $tmemberFinanceModel->$filed);
        money_change($type_arr, $tuid, $uid, $money_arr);

        $this->apiSuccess('转币成功');

    }

    /**
     * 充值申请
     */
    public
    function reReply()
    {
        $uid = $this->uid;
        $uinfo = Db('member')->find($uid);

        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }
        $data = input();
        $rule = [
            'money|充值金额' => 'require',
            'icon|打款截图' => 'require'
        ];
        $validata = new Validate($rule);
        if (!$validata->check($data)) {
            $this->apiError($validata->getError());
        }
        $data['userid'] = $uid;
        $data['hasmoney'] = $uinfo['hasmoney'];

        unset($data['token']);
        $res = Db('recharge')->insert($data);
        if ($res) {
            $this->apiSuccess('充值申请成功');
        } else {
            $this->apiError('充值申请失败');
        }
    }

    /**
     * 充值记录
     */
    public
    function reRecord()
    {
        $uid = is_login();
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $status = input('status', -2);

        if ($status > -2) {
            $maps['status'] = $map['status'] = $status;
        }

        $maps['userid'] = $map['userid'] = $uid;

        $list = Db('Recharge')->where($map)->order('createtime desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        if (request()->isMobile()) {
            $list = Db('Recharge')->where($map)->order('createtime desc')->select();
        }
        $this->assign('_list', $list);
        $this->assign('page', $page);
        /*追加查询条件*/
        $arr = [
            [
                'type' => 'select',
                'name' => 'status',
                'inputid' => '',
                'readonly' => '',
                'title' => '状态',
                'option' => [
                    -2 => '全部',
                    -1 => '拒批',
                    0 => '尚未审核',
                    1 => '同意'
                ],
                'value' => $status,
            ]
        ];
        $this->searchCondition($maps, $arr);
        $this->assign('title', "充值");
        return $this->fetch('rerecord');
    }


    public
    function reRecord1()
    {
        $uid = is_login();

        $map['moneytype'] = 3;
        $map['userid'] = $uid;
        $list = Db('Recharge')->where($map)->order('createtime desc')->select();
        $this->assign('_list', $list);
        $this->assign('title', "充值");
        return $this->fetch();
    }

    /**
     * 申请成为报单中心
     */
//    public function billReplay(){
//    	$uid = is_login();
//    	$info = self::$Member->where(array('uid'=>$uid))->field('isbill')->find();
//    	if(IS_POST){
//
//    	}else{
//			$this->assign('info',$info);
//    		$this->title="升级申请";
//    		$this->display();
//    	}
//    }

    /**
     * 财务流水
     */
    public function financialFlow()
    {
        $page = input('page');
        $start = ($page - 1) * self::$totalList;
        $uid = $this->uid;

        $moneytype = input('moneytype', 1);
        $recordtype = input('recordtype', -1);
        $remark = input('remark');
        $map = [
            'targetuserid' => $uid,
            'moneytype' => $moneytype
        ];

        if ($recordtype > -1) {
            $map['recordtype'] = $recordtype;
        }

        if ($remark === 'trader') {
            $map['remark'] = $remark;
        } else {
            $map['remark'] = ['<>', 'trader'];
        }

        $totalCount = Db('money_change')
            ->where($map)
            ->count();

        $list = Db('money_change')
            ->where($map)
            ->order('createtime desc,id desc')
            ->limit($start, self::$totalList)
            ->select();

        if ($totalCount > 0) {
            $changetypes = config('changetype');
//            $moneytypes = config('moneytype');
            foreach ($list as &$val) {
                $val['createtime'] = date('Y-m-d H:i:s', $val['createtime']);
                $val['changetype'] = $changetypes[$val['changetype']];
                $val['money'] = number_format($val['money'], 2);
            }
        }

        $this->apiSuccess('财务流水', ['data' => $list, 'totalCount' => $totalCount]);
    }

    /**
     * 资金管理
     */
    public
    function finance()
    {
        $uid = is_login();
        $user = Db('member')->where('uid', $uid)->find();
        /*累计收入*/
        $bonusTotal = Db('bonus_total')->where('userid', $uid)->find();

        $this->assign('user', $user);
        $this->assign('bonusTotal', $bonusTotal);
        $this->assign('title', '累计收益');
        return $this->fetch();
    }
}